<template>
  <globle-dialog ref="globleDialogRef" :title="globleDialogConfig.title"  @onClickConfirmBtn="onConfirm"
    @onClickCancelBtn="onCancel" @onDialogColsed="onDialogClosed" @onBeforeColse="onBeforeColse">
    <div class="add-tch">
      <article>选择的教师：</article>
      <el-table v-if="tchList.length" :border="true" stripe :data="tchList" cell-class-name="table-cell"
        header-cell-class-name="table-header-cell">
        <el-table-column property="workId" label="工号" show-overflow-tooltip />
        <el-table-column property="name" label="姓名" />
        <el-table-column label="性别">
          <template #default="scope">{{ scope.row.sex === 1 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" icon="RefreshRight" @click="onReSelect">重新选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <globle-form ref="globleFormRef" :bindData="globleFormConfig.bindData"
      :itemConfig="globleFormConfig.itemConfig"></globle-form>
  </globle-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { APIData, ITch, ICourse } from '../../../../type';
import { formType, IGlobleFormProps, ISelectOption } from '../../../../components/form/type';
import { useAPI } from '../../../../request/api';
import { ElMessage, ElMessageBox } from 'element-plus';

let weekList = [] as ISelectOption[];
let weekDayList = [] as ISelectOption[];
let orderNumList = [] as ISelectOption[];
const tchList = ref([] as ITch[]);
const isAdd = ref<boolean>(false);
const api = useAPI();
const globleDialogRef = ref();
const globleFormRef = ref();
const errorNecessaryMsg = '这是必填项';
const globleDialogConfig = { title: '课程信息' };
const globleFormConfig: IGlobleFormProps = reactive({
  bindData: {} as ICourse,
  itemConfig: [
    {
      type: formType.input,
      label: '学年',
      prop: 'schoolYear',
      placeholder: '请输入学年,例2022-2023',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.select,
      label: '学期',
      prop: 'stage',
      isShow: true,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'change' }],
      options: [{ label: '第一学期', value: 1 }, { label: '第二学期', value: 2 }],
    },
    {
      type: formType.input,
      label: '年级',
      prop: 'grade',
      placeholder: '请输入年级,例2019',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '课程代码',
      prop: 'courseCode',
      placeholder: '请输入课程代码',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '课程名称',
      prop: 'courseName',
      placeholder: '请输入课程名称',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '教学班',
      prop: 'teachClass',
      placeholder: '请输入教学班',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '开课类型',
      prop: 'courseType',
      placeholder: '请输入开课类型',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '学时类型',
      prop: 'classHourType',
      placeholder: '请输入学时类型',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '开课学院',
      prop: 'openCollege',
      placeholder: '请输入开课学院',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '课程学分',
      prop: 'credit',
      placeholder: '请输入课程学分',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '任务人数',
      prop: 'maxPerson',
      placeholder: '请输入任务人数',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.input,
      label: '总学时',
      prop: 'totalHours',
      placeholder: '请输入总学时',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.multipleSelect,
      label: '课程周数',
      prop: 'week',
      isShow: true,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
      options: weekList,
    },
    {
      type: formType.multipleSelect,
      label: '课程星期',
      prop: 'weekDay',
      isShow: true,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
      options: weekDayList,
    },
    {
      type: formType.multipleSelect,
      label: '课程序号',
      prop: 'orderNum',
      isShow: true,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
      options: orderNumList,
    },
    {
      type: formType.input,
      label: '上课地点',
      prop: 'place',
      placeholder: '请输入上课地点',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    },
    {
      type: formType.colorPicker,
      label: '课程展示颜色',
      prop: 'color',
      labelWidth: 108,
    },
    {
      type: formType.textarea,
      label: '面向对象',
      prop: 'allowBand',
      width: 510,
      placeholder: '请输入面向对象',
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'blur' }],
    }
  ],
});

const openDialogByEdit = async (courseId: string) => {
  globleDialogRef.value.isShowDialog = true;
  const res: APIData = await api.course.findOne({ courseId });
  if (res.code == 200) globleFormConfig.bindData = res.data;
  else ElMessage.error('课程信息请求错误，请重试')

  getTchInfo(globleFormConfig.bindData.workId);
};

onMounted(() => {
  for (let i = 1; i <= 16; i++) weekList.push({ label: '第' + i + '周', value: String(i) })
  for (let i = 1; i <= 7; i++) weekDayList.push({ label: chineseWeedDay(i), value: String(i) });
  for (let i = 1; i <= 12; i++) orderNumList.push({ label: chineseOrderNum(i), value: String(i) });
})

const openDialogByAdd = (list: ITch[]) => {
  tchList.value = list;
  isAdd.value = true;
  globleDialogRef.value.isShowDialog = true;
  // const formEl = globleFormRef.value.formRef;
  // formEl.resetFields();
  globleFormConfig.bindData = {};
};

const emit = defineEmits(['onReGetData', 'onReSelect']);
const onReSelect = () => {
  emit('onReSelect');
}

//点击确定
const onConfirm = () => {
  const formEl = globleFormRef.value.formRef;
  formEl.validate((valid: boolean) => {
    if (valid)
      save().then(code => {
        if (code === 200) {
          emit('onReGetData');
          reset();
        }
      });
    else return false;
  });
};

//点击取消
const onCancel = () => {
  ElMessageBox.confirm('关闭将不保存更改的数据，确定继续吗').then(() => {
    reset();
    ElMessage.success('您取消了操作');
  }).catch(() => {
    // catch error
  })
};

//监听弹窗开启
const onDialogClosed = () => {
  const formEl = globleFormRef.value.formRef;
  formEl.clearValidate();
};

//卸载操作
const reset = () => {
  globleDialogRef.value.isShowDialog = false;
  const formEl = globleFormRef.value.formRef;
  globleFormConfig.bindData = {};
  isAdd.value = false;
  formEl.resetFields();
};

//监听弹窗关闭之前
const onBeforeColse = () => {
  ElMessageBox.confirm('关闭将不保存更改的数据，确定继续吗').then(() => {
    reset();
  }).catch(() => {
    // catch error
  })
};

const save = async () => {
  // let lastCode = 0;
  const formData = globleFormConfig.bindData;
  formData.orderNum = globleFormConfig.bindData.orderNum.sort().join(',')
  formData.week = globleFormConfig.bindData.week.sort().join(',')
  formData.weekDay = globleFormConfig.bindData.weekDay.sort().join(',')
  if (isAdd.value) {
    // let codeList = [] as any[];
    // tchList.value.forEach(async item => {
    formData.workId = tchList.value[0].workId;
    const res: APIData = await api.course.save(formData);
    if (res.code === 200) ElMessage.success('添加成功');
    else ElMessage.error(res.message);
    return res.code
    // codeList.push(res.code);
    // });
    // let flag = true;
    // for (const item of codeList) {
    //   if (item !== 200) flag = false;
    // }
    // if (flag) lastCode = 200;
  } else {
    const res: APIData = await api.course.save(formData);
    if (res.code === 200) ElMessage.success('修改成功');
    else ElMessage.error(res.message);
    // lastCode = res.code as number;
    return res.code
  }

  // return lastCode;
};

const getTchInfo = async (workId: string) => {
  const params = { workId }
  const res: APIData = await api.getUserInfo(params, 'teacher');
  if (res.code == 200) tchList.value = [res.data]
  else ElMessage.error('教师信息请求错误，请重试')
}

// 转中文星期  计算属性
const chineseWeedDay = (weekDay: number) => {
  switch (weekDay) {
    case 1: return '星期一';
    case 2: return '星期二';
    case 3: return '星期三';
    case 4: return '星期四';
    case 5: return '星期五';
    case 6: return '星期六';
    case 7: return '星期天';
    default: return ''
  }
}
const numWeedDay = (weekDay: string) => {
  switch (weekDay) {
    case '星期一': return 1;
    case '星期二': return 2;
    case '星期三': return 3;
    case '星期四': return 4;
    case '星期五': return 5;
    case '星期六': return 6;
    case '星期天': return 7;
    default: return ''
  }
}

// 转中文课程序号  计算属性
const chineseOrderNum = (orderNum: number) => {
  switch (orderNum) {
    case 1: return '第一节';
    case 2: return '第二节';
    case 3: return '第三节';
    case 4: return '第四节';
    case 5: return '第五节';
    case 6: return '第六节';
    case 7: return '第七节';
    case 8: return '第八节';
    case 9: return '第九节';
    case 10: return '第十节';
    case 11: return '第十一节';
    case 12: return '第十二节';
    default: return ''
  }
}

defineExpose({
  openDialogByEdit,
  openDialogByAdd,
});
</script>

<style lang="scss" scoped>
.add-tch {
  article {
    font-size: 18px;
    font-weight: bold;
  }

  p {
    display: inline-block;
    font-weight: bold;
    margin-top: 4px;
    margin-right: 16px;
  }

  padding: 8px;
  padding-top: 0;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 16px;
}
</style>
